"""本文件包含应用程序的图模式。"""

import re
import uuid
from typing import Literal, Optional

from typing_extensions  import Annotated, TypedDict

from copilotkit import CopilotKitState
from langgraph.graph.message import add_messages
from pydantic import (
    BaseModel,
    Field,
    field_validator,
)


class GraphState(BaseModel):
    """LangGraph Agent/工作流的状态定义。"""

    messages: Annotated[list, add_messages] = Field(
        default_factory=list, description="The messages in the conversation"
    )
    session_id: str = Field(..., description="The unique identifier for the conversation session")

    @field_validator("session_id")
    @classmethod
    def validate_session_id(cls, v: str) -> str:
        """验证会话 ID 是否为有效的 UUID 或遵循安全模式。

        Args:
            v: 要验证的线程 ID

        Returns:
            str: 验证后的会话 ID

        Raises:
            ValueError: 如果会话 ID 无效
        """
        # Try to validate as UUID
        try:
            uuid.UUID(v)
            return v
        except ValueError:
            # If not a UUID, check for safe characters only
            if not re.match(r"^[a-zA-Z0-9_\-]+$", v):
                raise ValueError("Session ID must contain only alphanumeric characters, underscores, and hyphens")
            return v

class Searches(TypedDict):
    query: str
    done: bool

class SampleGraphState(CopilotKitState):
    agent_name: str
    session_id: str
    searches: list[Searches]
    language: Literal["english", "chinese"]
    knowledge_index: Optional[str]
    knowledge: Optional[str]